﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading;

namespace iLangl.Utils
{
	public class BaseMockupStorageManager
	{
		protected FileSystemWatcher storageWatcher;
		protected String _filename = string.Empty;
		static ReaderWriterLock rwl = new ReaderWriterLock();
		public int ChaneEventRiseAmmount = 0;
		public BaseMockupStorageManager(String filename)
		{
			_filename = filename;
			storageWatcher = new FileSystemWatcher(Path.GetDirectoryName(filename));
			storageWatcher.Filter = Path.GetFileName(filename);
			storageWatcher.Changed += new FileSystemEventHandler(storageWatcher_Changed);
			storageWatcher.NotifyFilter = NotifyFilters.Size;
			startListen();
		}

		protected String StorageFileName
		{
			get
			{
				return _filename;
			}
		}

		protected void stopListen()
		{
			storageWatcher.EnableRaisingEvents = false;
		}

		protected void startListen()
		{
			storageWatcher.EnableRaisingEvents = true;
		}

		DateTime current = DateTime.Now;
		void storageWatcher_Changed(object sender, FileSystemEventArgs e)
		{
			ChaneEventRiseAmmount++;

			if ((DateTime.Now - current).TotalSeconds > 5)
			{
				current = DateTime.Now;
			}
			else
			{
				return;
			}
			Thread.Sleep(1000);
			changed();
			
		}

		protected virtual void changed()
		{
			read();
		}

		protected virtual void read()
		{
			rwl.AcquireReaderLock(milliseckonds);

			try
			{
				readStorage();
			}
			finally
			{
				rwl.ReleaseReaderLock();
			}
		}
		protected virtual void saveStorage()
		{
		}

		int milliseckonds = 1000;
		protected static object iomutex = new object();
		protected virtual void Save()
		{
			stopListen();
			rwl.AcquireWriterLock(milliseckonds);
			try
			{

				saveStorage();
			}
			finally
			{
				rwl.ReleaseWriterLock();
			}

			startListen();
		}

		protected virtual void readStorage()
		{
		}
	
	}
}
